#!/bin/bash

# Nginx Uninstall Script
# Function: Remove nginx installation and related configurations
# Compatible: Anolis OS 7.9 and other Linux distributions
# Author: System Administrator
# Date: $(date +%Y-%m-%d)
#
# Usage Instructions:
# 1. Run with root privileges: sudo ./nginx_uninstall.sh
# 2. Script will stop nginx service, remove systemd service file,
#    and optionally remove installation directory and nginx user

# set -e  # Don't exit on error for uninstall script

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Installation path
NGINX_INSTALL_DIR="/opt/RadMedical/product/tool/nginx"

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_question() {
    echo -e "${BLUE}[QUESTION]${NC} $1"
}

# Check if running as root user
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script requires root privileges to run"
        exit 1
    fi
}

# Show installation information
show_installation_info() {
    log_info "=========================================="
    log_info "nginx Uninstall Script"
    log_info "=========================================="
    log_info "Installation path: $NGINX_INSTALL_DIR"
    log_info "Service file: /etc/systemd/system/nginx.service"
    log_info "=========================================="
    echo ""
}

# Stop nginx service
stop_nginx_service() {
    log_info "Stopping nginx service..."
    
    if systemctl is-active --quiet nginx 2>/dev/null; then
        systemctl stop nginx
        log_info "nginx service stopped successfully"
    else
        log_warn "nginx service is not running"
    fi
}

# Disable nginx service
disable_nginx_service() {
    log_info "Disabling nginx service..."
    
    if systemctl is-enabled --quiet nginx 2>/dev/null; then
        systemctl disable nginx
        log_info "nginx service disabled successfully"
    else
        log_warn "nginx service is not enabled"
    fi
}

# Remove systemd service file
remove_systemd_service() {
    log_info "Removing systemd service file..."
    
    local service_file="/etc/systemd/system/nginx.service"
    
    if [[ -f "$service_file" ]]; then
        rm -f "$service_file"
        log_info "Service file removed: $service_file"
        
        # Reload systemd daemon
        systemctl daemon-reload
        log_info "Systemd daemon reloaded"
    else
        log_warn "Service file not found: $service_file"
    fi
}

# Remove installation directory
remove_installation_directory() {
    log_info "Checking installation directory..."
    
    if [[ -d "$NGINX_INSTALL_DIR" ]]; then
        log_info "Found installation directory: $NGINX_INSTALL_DIR"
        
        read -p "Do you want to remove the installation directory? (y/N): " -n 1 -r
        echo
        
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Removing installation directory..."
            rm -rf "$NGINX_INSTALL_DIR"
            log_info "Installation directory removed successfully"
        else
            log_warn "Installation directory kept: $NGINX_INSTALL_DIR"
        fi
    else
        log_warn "Installation directory not found: $NGINX_INSTALL_DIR"
    fi
}

# Remove nginx user (optional)
remove_nginx_user() {
    log_info "Checking nginx user..."
    
    if id "nginx" &>/dev/null; then
        log_info "nginx user exists"
        
        read -p "Do you want to remove the nginx user? (y/N): " -n 1 -r
        echo
        
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Removing nginx user..."
            userdel -r nginx 2>/dev/null || userdel nginx
            log_info "nginx user removed successfully"
        else
            log_warn "nginx user kept"
        fi
    else
        log_warn "nginx user does not exist"
    fi
}

# Remove installed packages (optional)
remove_installed_packages() {
    log_info "Checking installed packages..."
    
    log_question "Do you want to remove the installed dependency packages?"
    log_info "  - gcc, make, pcre-devel, zlib-devel, openssl-devel"
    read -p "Remove packages? (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_warn "Removing installed packages may affect other software!"
        
        # Detect system type
        if [[ -f /etc/os-release ]]; then
            source /etc/os-release
            
            if [[ "$ID" == "anolis" ]] || [[ "$ID" == "centos" ]] || [[ "$ID" == "rhel" ]]; then
                log_info "Detected RedHat series system"
                log_info "Removing: gcc make pcre-devel zlib-devel openssl-devel"
                
                # Remove only nginx-specific development libraries
                # Be careful with gcc and make as they may be needed by other software
                read -p "Also remove gcc and make? This may affect other software! (y/N): " -n 1 -r
                echo
                
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    yum remove -y gcc make pcre-devel zlib-devel openssl-devel 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                else
                    yum remove -y pcre-devel zlib-devel openssl-devel 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                fi
            elif [[ "$ID" == "ubuntu" ]] || [[ "$ID" == "debian" ]]; then
                log_info "Detected Debian series system"
                log_info "Removing: gcc make libpcre3-dev zlib1g-dev libssl-dev"
                
                read -p "Also remove gcc and make? This may affect other software! (y/N): " -n 1 -r
                echo
                
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    apt-get remove -y gcc make libpcre3-dev zlib1g-dev libssl-dev 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                else
                    apt-get remove -y libpcre3-dev zlib1g-dev libssl-dev 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                fi
            else
                log_warn "Unknown system type, skipping package removal"
            fi
            
            log_info "Package removal completed"
        else
            log_warn "Unable to detect system type for package removal"
        fi
    else
        log_info "Skipping package removal"
    fi
}

# Check if nginx is running
check_nginx_running() {
    if pgrep -f "$NGINX_INSTALL_DIR/sbin/nginx" >/dev/null; then
        log_warn "nginx process is still running"
        log_warn "Attempting to stop it..."
        
        # Try to find the PID
        local pid=$(pgrep -f "$NGINX_INSTALL_DIR/sbin/nginx" | head -n1)
        if [[ -n "$pid" ]]; then
            kill -9 "$pid" 2>/dev/null && log_info "Stopped nginx process (PID: $pid)"
        fi
    fi
}

# Verify uninstallation
verify_uninstallation() {
    log_info "Verifying uninstallation..."
    
    local issues_found=false
    
    # Check if service is still running
    if systemctl is-active --quiet nginx 2>/dev/null; then
        log_error "nginx service is still active"
        issues_found=true
    fi
    
    # Check if service file still exists
    if [[ -f /etc/systemd/system/nginx.service ]]; then
        log_error "Service file still exists: /etc/systemd/system/nginx.service"
        issues_found=true
    fi
    
    # Check if binary still exists
    if [[ -f "$NGINX_INSTALL_DIR/sbin/nginx" ]]; then
        log_warn "nginx binary still exists: $NGINX_INSTALL_DIR/sbin/nginx"
    fi
    
    if [[ $issues_found == false ]]; then
        log_info "Uninstallation verification passed"
    else
        log_error "Uninstallation verification found some issues"
    fi
}

# Show completion message
show_completion_message() {
    log_info "=========================================="
    log_info "nginx uninstallation completed!"
    log_info "=========================================="
    log_info ""
    log_info "Summary:"
    log_info "  ✓ nginx service stopped"
    log_info "  ✓ nginx service disabled"
    log_info "  ✓ systemd service file removed"
    log_info "  ✓ Installation directory (if confirmed)"
    log_info "  ✓ nginx user (if confirmed)"
    log_info ""
    log_info "Note: If you need to reinstall nginx, run the installation script again"
    log_info "=========================================="
}

# Main function
main() {
    log_info "Starting nginx uninstallation..."
    
    # Check root privileges
    check_root
    
    # Show installation information
    show_installation_info
    
    # Confirmation
    log_warn "This script will:"
    log_warn "  1. Stop nginx service"
    log_warn "  2. Disable nginx service"
    log_warn "  3. Remove systemd service file"
    log_warn "  4. Optionally remove installation directory"
    log_warn "  5. Optionally remove nginx user"
    log_warn "  6. Optionally remove dependency packages"
    echo ""
    
    read -p "Do you want to continue? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Uninstallation cancelled"
        exit 0
    fi
    
    # Stop nginx service
    stop_nginx_service
    
    # Additional check for running processes
    check_nginx_running
    
    # Disable nginx service
    disable_nginx_service
    
    # Remove systemd service file
    remove_systemd_service
    
    # Remove installation directory
    remove_installation_directory
    
    # Remove nginx user
    remove_nginx_user
    
    # Optional: Remove installed packages
    echo ""
    remove_installed_packages
    
    # Verify uninstallation
    verify_uninstallation
    
    # Show completion message
    show_completion_message
    
    log_info "nginx uninstallation script execution completed!"
}

# Execute main function
main "$@"
